package com.fit.utils.ee;

import com.fit.utils.se.EmptyUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * spring SpringUtil 工具类
 * 此工具类只适用于web项目
 * @author hcl
 *
 	 *注意：
 	 * 如果有用到HttpServletRequest对象,需要这web.xml中注册以下监听器
	 *
	<!-- springMvc  request监听器 -->
	<listener>
		<listener-class>
			org.springframework.web.context.request.RequestContextListener
		</listener-class>
	</listener>
 *
 */
public class SpringUtil {
	

	
	/**
	 * 获取HttpServletRequest对象
	 * @return
	 */
	public static HttpServletRequest getRequest(){
		ServletRequestAttributes servletRequestAttributes = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes());
		if(servletRequestAttributes == null){
			return null;
		}
		return servletRequestAttributes.getRequest();
	}

	/**
	 * 获取HttpServletRequest对象
	 * @return
	 */
	public static HttpServletResponse getResponse(){
		ServletRequestAttributes servletRequestAttributes = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes());
		if(servletRequestAttributes == null){
			return null;
		}
		return servletRequestAttributes.getResponse();
	}


	/**
	 * @describe: 设置下载文件
	 * @author: hcl  
	 * @date: 2018/6/11 11:04
	 * @param: [fileName]  
	 * @return void  
	 */
	public static void setDownloadFileName(String fileName){
        SpringUtil.setDownloadFileName(SpringUtil.getResponse(),fileName);
	}

	/**
	 * @describe: 设置下载文件名称
	 * @author: hcl  
	 * @date: 2018/6/11 11:04
	 * @param: [httpServletResponse, fileName]  
	 * @return void  
	 */
	public static void setDownloadFileName(HttpServletResponse httpServletResponse,String fileName){
		if(EmptyUtils.isEmpty(fileName)){
            fileName = "下载文件";
        }
        try {
		    fileName = URLEncoder.encode(fileName, "UTF-8");
		    //设置文件名称
            httpServletResponse.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
            // 设置强制下载不打开
            httpServletResponse.addHeader("Content-Type","application/force-download");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("编码转换异常！",e);
        }
    }

	/**
	 * 获取session对象
	 * @return
	 */
	public static HttpSession getSession(){
		return SpringUtil.getRequest().getSession();
	}
	

}
